<template>
  <div>
    <CrumBsofbread name1="权限管理" name2="角色列表" />

    <el-card>
      <el-row>
        <el-col>
          <el-button type="primary" @click="addDialogVisible = true"
            >添加角色</el-button
          >
        </el-col>
      </el-row>
      
      <el-table :data="roleslist" border stripe>
        <!-- 角色列表区域 -->
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-row :class="['bdbottom', i1 === 0 ? 'bdtop' : '', 'vcenter']" v-for="(item1, i1) in scope.row.children" :key="item1.id">
              <!-- 渲染一级权限 -->
              <el-col :span="5">
                <el-tag closable
                    @close="removeRightById(scope.row, item1.id)">{{item1.authName}}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 渲染二级和三级级权限 -->
              <el-col :span="19">
                 <!-- 通过for循环嵌套渲染二级权限  -->
                <el-row :class="[i2 === 0 ? '' : 'bdtop', 'vcenter']" v-for="(item2, i2) in item1.children" :key="item2.id">
                  <el-col :span="6">
                    <el-tag type="success" closable
                    @close="removeRightById(scope.row, item2.id)">{{item2.authName}}</el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <!-- 通过for循环嵌套渲染三级权限  -->
                  <el-col :span="18">
                    <el-tag type="warning" 
                    v-for="(item3) in item2.children" 
                    :key="item3.id" 
                    closable
                    @close="removeRightById(scope.row, item3.id)"
                    >
                    {{item3.authName}}</el-tag>
                  </el-col> 
                </el-row>
              </el-col>             
            </el-row>
          </template>
        </el-table-column>
        <el-table-column label="序号" type="index"></el-table-column>
        <el-table-column label="角色名称" prop="roleName"></el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
        <el-table-column label="操作" width="320px">
          <template slot-scope="scope">
            <!-- 修改按钮 -->
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="showEditDialog(scope.row.id)"
              >编辑</el-button
            >
            <!-- 删除按钮 -->
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="removeUserById(scope.row.id)"
              >删除</el-button
            >
            <!-- 分配角色按钮 -->
            <el-button type="warning" icon="el-icon-setting" size="mini" @click="showSetRightDialog(scope.row)"
              >分配权限</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 编辑对话框 -->
    <el-dialog
      title="编辑角色"
      :visible.sync="editDialogVisible"
      width="50%"
      @click="editDialogClosed"
    >
      <el-form
        :model="editRolesForm"
        :rules="editFormRules"
        ref="editFormRef"
        label-width="100px"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="editRolesForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="editRolesForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editFormInfo">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 添加角色对话框 -->
    <el-dialog
      title="添加角色"
      :visible.sync="addDialogVisible"
      @close="addDislogClosed"
    >
      <el-form
        :model="addRolesForm"
        :rules="addFormRules"
        ref="addRolesForm"
        label-width="100px"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="addRolesForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="addRolesForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 分配权限对话框 -->
    <el-dialog
      title="分配权限"
      :visible.sync="setRightDialogVisible"
      width="50%" @close="setRightDialogClose">
      <!-- 树形控件 -->
      <el-tree 
      show-checkbox 
      :data="rightslist" 
      :props="treeProps" 
      node-key="id" 
      default-expand-all
      :default-checked-keys="defkeys"
      ref="treeRef"
      ></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRightDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="allotRights">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import CrumBsofbread from "../CrumBsofbread.vue";
export default {
  components: {
    CrumBsofbread,
  },
  data() {
    return {
      //角色列表数据
      roleslist: [],
      // 添加角色对话框的显示和隐藏
      addDialogVisible: false,
      //控制修改用户对话框的显示与隐藏
      editDialogVisible: false,
      //控制权限对话框的显示与隐藏
      setRightDialogVisible: false,
      //添加用户的表单数据
      addRolesForm: {
        roleName: "",
        roleDesc: "",
      },
      //添加表单验证规则对象
      addFormRules: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur'}
        ],
        roleDesc: [
          { required: true, message: '请输入角色描述', trigger: 'blur'}
        ]
      },
      //编辑用户的表单数据
      editRolesForm: {},    
      //所有权限列表 树形控件的数据
      rightslist: [],
      //树形控件的属性绑定对象
      treeProps: {
        label: 'authName',
        children: 'children'
      },
      //默认选中的节点id值数组
      defkeys: [],
      //保存正在操作的角色id
      roleId:''
    };
  },
  created() {
    //获取权限列表数据
    this.getRolesList();
  },
  methods: {
    //获取权限列表数据
    async getRolesList() {
      const { data: res } = await this.$http.get("roles");
      if (res.meta.status !== 200) {
        return this.$message.error("获取角色列表失败！");
      }
      this.roleslist = res.data;
      //console.log(this.roleslist);
    },   
    //点击按钮 添加新角色
    addUser() {
      //调用validate进行表单验证
      this.$refs.addRolesForm.validate(async (valid) => {
        if (!valid) return this.$message.error("请填写完整用户信息! ");
        //发送请求完成添加用户的操作
        const { data: res } = await this.$http.post("roles", this.addRolesForm);
        //判断如果添加失败，就做提示
        if (res.meta.status !== 201) {
          return this.$message.error("添加用户失败! ");
        }
        //添加成功的提示
        this.$message.success("添加用户成功! ");
        this.addDialogVisible = false;
        //重新请求最新的数据
        this.getRolesList();
      });
    },
    //监听添加色对话框关闭 清空数据
    addDialogClosed() {
      this.$refs.addFormRef.resetFields();
    },
    // 编辑角色的信息
    async showEditDialog(id) {
      const { data: res } = await this.$http.get("roles/" + id);
      if (res.meta.status !== 200) {
        return this.$message.error("编辑角色失败!");
      }
      this.editRolesForm = res.data;
      //console.log(this.editRolesForm)
      this.editDialogVisible = true;
    },
    //关闭编辑用户对话框
    editDialogClosed() {
      this.$refs.editFormRef.resetFields();
    },
    //编辑角色并提交
    editFormInfo() {
      //用户点击修改表单中的确定按钮之后，验证表单数据
      this.$refs.editFormRef.validate(async (valid) => {
        if (!valid) return this.$message.error("请填写完整用户信息! ");
        //发送请求完成修改用户的操作
        const { data: res } = await this.$http.put(
          "roles/" + this.editRolesForm.roleId,
          {
            roleName: this.editRolesForm.roleName,
            roleDesc: this.editRolesForm.roleDesc,
          }
        );
        //判断如果修改失败，就做提示
        if (res.meta.status !== 200)
        return this.$message.error("编辑角色失败! ");
        this.$message.success("编辑角色成功");
        //关闭对话框
        this.editDialogVisible = false;
        //重新请求最新的数据
        this.getRolesList();
      });
    },
    //删除角色
    async removeUserById(id) {
      //弹出确定取消框，是否删除用户
      const confirmResult = await this.$confirm(
        "请问是否要永久删除该用户",
        "删除提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((err) => err);
      //如果用户点击确认，则confirmResult 为'confirm'
      //如果用户点击取消, 则confirmResult获取的就是catch的错误消息'cancel'
      if (confirmResult != "confirm") {
        return this.$message.info("已经取消删除");
      }
      //发送请求根据id完成删除操作
      const { data: res } = await this.$http.delete("roles/" + id);
      if (res.meta.status !== 200) return this.$message.error("删除角色失败! ");
      this.$message.success("删除角色成功");
      //重新请求最新的数据
      this.getRolesList();
    },
    //根据id删除权限功能
    async removeRightById(role, rightId) {
      const confirmResult = await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
          confirmButtonText: '确定删除',
          cancelButtonText: '取消',
          type: 'warning'
        }).catch(err => err)
        if (confirmResult != 'confirm') {
          return this.$message.info('已取消删除')
        }
        //发送请求 
        const { data: res } = await this.$http.delete(`roles/${role.id}/rights/${rightId}`)
        if (res.meta.status !== 200)
        return this.$message.error('删除角色权限失败!')
        this.$message.success('删除角色权限成功')
        //this.getRolesList()
        //权限进行更新
        role.children = res.data
    },
    //权限对话框
    async showSetRightDialog(role) {
      //将role.id保存起来以供保存权限时使用
      this.roleId = role.id
      //获取所以权限数据
      const { data: res } = await this.$http.get('rights/tree')
      if (res.meta.status !== 200) {
        return this.$message.error('获取权限数据失败！')
      }
      //获取数据保存到data中
      this.rightslist = res.data
      //console.log(this.rightslist);
      this.getLeafkeys(role, this.defkeys)
      //当点击分配权限按钮时，展示对应的对话框
      this.setRightDialogVisible = true
    },
    //通过梯归形式 获取角色所以三角权限id 保存到defkeys数组中
    getLeafkeys(node, arr) {
      if (!node.children) {
        return arr.push(node.id)
      }
      node.children.forEach(item =>
      this.getLeafkeys(item, arr))
    },
    //权限对话框关闭 清空数据
    setRightDialogClose() {
      this.defkeys = []
    },
    //点击为角色分配权限
    async allotRights() {
      //获取所有选中及半选的内容
      const keys = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys()
      ]
      //将数组转换为 , 拼接的字符串
      const idStr = keys.join(',')
      const { data: res } = await this.$http.post(`roles/${this.roleId}/rights`,
      { rids: idStr})
      if (res.meta.status !== 200) 
      return this.$message.error('分配权限失败！')
      this.$message.success('分配权限成功')
      this.getRolesList()
      this.setRightDialogVisible = false
    }
  },
};
</script>

<style lang="less" scoped>
.el-tag {
  margin: 7px;
}
.bdtop {
  border-top: 1px solid #eee;
}
.bdbottom {
  border-bottom: 1px solid #eee;
}
.vcenter {
  display: flex;
  align-items: center;
}
</style>